package net.nohaven.proj.javeau.fs.real;

import java.io.File;
import java.util.Date;

import net.nohaven.proj.javeau.fs.exceptions.EntityNotFoundException;
import net.nohaven.proj.javeau.fs.model.FSDirectory;
import net.nohaven.proj.javeau.fs.model.FSItem;
import net.nohaven.proj.javeau.utils.Utils;

public class RFSDirectory implements FSDirectory {
	protected File dir;
	private String name;

	public RFSDirectory(String path) throws EntityNotFoundException {
		this(new File(path));
	}

	public RFSDirectory(File dir) throws EntityNotFoundException {
		if (!dir.exists() || !dir.isDirectory())
			throw new EntityNotFoundException(
					"Invalid path : it's not a directory");
		this.dir = dir;
		this.name = dir.getName();
		if (Utils.isEmpty(name))
			name = dir.getPath();
	}

	protected RFSDirectory() {

	}

	public boolean canWrite() {
		return dir.canWrite();
	}

	public Date getModificationDate() {
		return new Date(dir.lastModified());
	}

	public String getName() {
		return name;
	}

	protected void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return dir.getAbsolutePath();
	}

	public RFSDirectory getParent() {
		if (dir.getParent() != null)
			try {
				return new RFSDirectory(dir.getParentFile());
			} catch (EntityNotFoundException e) {
				try {
					return new RFSRoots();
				} catch (EntityNotFoundException e1) {
				}
			}
		else
			try {
				return new RFSRoots();
			} catch (EntityNotFoundException e) {
			}
		return null; //never actually reached
	}

	public FSItem[] getContents() {
		File[] files = dir.listFiles();

		FSItem[] ret = new FSItem[files.length + 1];

		RFSDirectory dotdot = getParent();
		dotdot.setName("..");
		ret[0] = dotdot;

		for (int i = 0; i < files.length; i++)
			try {
				if (files[i].isDirectory())
					ret[1 + i] = new RFSDirectory(files[i]);
				else
					ret[1 + i] = new RFSFile(files[i]);
			} catch (EntityNotFoundException e) {
				e.printStackTrace();
				continue;
			}

		return ret;
	}

	public boolean isDevice() {
		return getName().length() == 3 && getName().charAt(1) == ':'; //baaaad
	}

	public FSItem get(String name) {
		File f = new File(dir, name);
		if (!f.exists())
			return null;
		try {
			if (f.isDirectory())
				return new RFSDirectory(f);
			return new RFSFile(f);
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
}
